package com.sddnytsh.body_buildingsystem.components

import android.graphics.Bitmap
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CameraAlt
import androidx.compose.material.icons.filled.Photo
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import coil.compose.AsyncImage
import com.sddnytsh.body_buildingsystem.R
import com.sddnytsh.body_buildingsystem.services.AvatarService
import com.sddnytsh.body_buildingsystem.utils.AvatarCache
import android.util.Log

/**
 * 默认头像选择对话框
 */
@Composable
fun DefaultAvatarSelectionDialog(
    onAvatarSelected: (String) -> Unit,
    onDismiss: () -> Unit
) {
    // 10张不同的风景和动漫头像URL
    val defaultAvatars = listOf(
        "https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=150&h=150&fit=crop&crop=center", // 山景
        "https://images.unsplash.com/photo-1441974231531-c6227db76b6e?w=150&h=150&fit=crop&crop=center", // 森林
        "https://images.unsplash.com/photo-1439066615861-d1af74d74000?w=150&h=150&fit=crop&crop=center", // 湖泊
        "https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=150&h=150&fit=crop&crop=center", // 海滩
        "https://images.unsplash.com/photo-1519501025264-65ba15a82390?w=150&h=150&fit=crop&crop=center", // 城市
        "https://images.unsplash.com/photo-1444927714506-8492d94b5ba0?w=150&h=150&fit=crop&crop=center", // 星空
        "https://images.unsplash.com/photo-1490750967868-88aa4486c946?w=150&h=150&fit=crop&crop=center", // 花朵
        "https://images.unsplash.com/photo-1513475382585-d06e58bcb0e0?w=150&h=150&fit=crop&crop=center", // 云朵
        "https://images.unsplash.com/photo-1416879595882-3373a0480b5b?w=150&h=150&fit=crop&crop=center", // 日落
        "https://images.unsplash.com/photo-1421789497144-f50500b5fcf0?w=150&h=150&fit=crop&crop=center"  // 雪景
    )
    
    Dialog(onDismissRequest = onDismiss) {
        Surface(
            modifier = Modifier
                .fillMaxWidth()
                .wrapContentHeight(),
            shape = MaterialTheme.shapes.large,
            color = MaterialTheme.colorScheme.surface
        ) {
            Column(
                modifier = Modifier.padding(24.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(
                    text = "选择默认头像",
                    style = MaterialTheme.typography.titleLarge.copy(
                        fontWeight = FontWeight.Bold
                    )
                )
                
                Spacer(modifier = Modifier.height(16.dp))
                
                // 头像网格 - 调整为3列，更好地显示10张头像
                LazyVerticalGrid(
                    columns = GridCells.Fixed(3),
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp),
                    modifier = Modifier.height(240.dp)
                ) {
                    items(defaultAvatars.size) { index ->
                        AsyncImage(
                            model = defaultAvatars[index],
                            contentDescription = "默认头像${index + 1}",
                            modifier = Modifier
                                .size(70.dp)
                                .clip(CircleShape)
                                .clickable {
                                    onAvatarSelected(defaultAvatars[index])
                                    onDismiss()
                                },
                            contentScale = ContentScale.Crop
                        )
                    }
                }
                
                Spacer(modifier = Modifier.height(16.dp))
                
                // 取消按钮
                TextButton(
                    onClick = onDismiss,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Text("取消")
                }
            }
        }
    }
}

/**
 * 头像选择对话框
 */
@Composable
fun AvatarSelectionDialog(
    currentAvatar: String?,
    currentName: String,
    isUploading: Boolean,
    onSelectFromGallery: () -> Unit,
    onTakePhoto: () -> Unit,
    onUseDefaultAvatar: () -> Unit,
    onDismiss: () -> Unit
) {
    Dialog(onDismissRequest = onDismiss) {
        Surface(
            modifier = Modifier
                .fillMaxWidth()
                .wrapContentHeight(),
            shape = MaterialTheme.shapes.large,
            color = MaterialTheme.colorScheme.surface
        ) {
            Column(
                modifier = Modifier.padding(24.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                // 标题
                Text(
                    text = "选择头像",
                    style = MaterialTheme.typography.titleLarge.copy(
                        fontWeight = FontWeight.Bold
                    ),
                    modifier = Modifier.padding(bottom = 16.dp)
                )
                
                // 当前头像预览
                CurrentAvatarPreview(
                    currentAvatar = currentAvatar,
                    currentName = currentName,
                    modifier = Modifier.padding(bottom = 24.dp)
                )
                
                // 选择选项
                Column(
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    // 从相册选择
                    AvatarOptionButton(
                        icon = Icons.Default.Photo,
                        text = "从相册选择",
                        onClick = onSelectFromGallery,
                        enabled = !isUploading
                    )
                    
                    // 拍照
                    AvatarOptionButton(
                        icon = Icons.Default.CameraAlt,
                        text = "拍照",
                        onClick = onTakePhoto,
                        enabled = !isUploading
                    )
                    
                    // 选择默认头像
                    AvatarOptionButton(
                        icon = null,
                        text = "选择默认头像",
                        onClick = onUseDefaultAvatar,
                        enabled = !isUploading
                    )
                }
                
                Spacer(modifier = Modifier.height(16.dp))
                
                // 取消按钮
                TextButton(
                    onClick = onDismiss,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Text("取消")
                }
            }
        }
    }
}

/**
 * 当前头像预览
 */
@Composable
fun CurrentAvatarPreview(
    currentAvatar: String?,
    currentName: String,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            text = "当前头像",
            style = MaterialTheme.typography.bodyMedium.copy(
                color = MaterialTheme.colorScheme.onSurfaceVariant
            ),
            modifier = Modifier.padding(bottom = 8.dp)
        )
        
        Box(
            modifier = Modifier
                .size(80.dp)
                .clip(CircleShape)
                .border(
                    width = 2.dp,
                    color = MaterialTheme.colorScheme.outline,
                    shape = CircleShape
                ),
            contentAlignment = Alignment.Center
        ) {
            if (currentAvatar != null && currentAvatar.isNotEmpty()) {
                // 显示自定义头像
                SimpleAvatarImage(
                    avatarUrl = currentAvatar,
                    fallbackName = currentName,
                    size = 80.dp
                )
            } else {
                // 显示默认头像
                DefaultAvatar(
                    name = currentName,
                    size = 80.dp
                )
            }
        }
    }
}

/**
 * 头像选项按钮
 */
@Composable
fun AvatarOptionButton(
    icon: androidx.compose.ui.graphics.vector.ImageVector?,
    text: String,
    onClick: () -> Unit,
    enabled: Boolean = true,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .fillMaxWidth()
            .clickable(enabled = enabled) { onClick() },
        colors = CardDefaults.cardColors(
            containerColor = if (enabled) MaterialTheme.colorScheme.surfaceVariant else MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            if (icon != null) {
                Icon(
                    imageVector = icon,
                    contentDescription = text,
                    tint = if (enabled) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f),
                    modifier = Modifier.size(24.dp)
                )
                Spacer(modifier = Modifier.width(12.dp))
            }
            Text(
                text = text,
                style = MaterialTheme.typography.bodyLarge.copy(
                    color = if (enabled) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)
                )
            )
        }
    }
}

/**
 * 头像图片组件
 */
@Composable
fun AvatarImage(
    avatarUrl: String,
    fallbackName: String,
    size: androidx.compose.ui.unit.Dp = 48.dp,
    modifier: Modifier = Modifier
) {
    // 暂时使用默认头像，避免Composable上下文问题
    // TODO: 实现网络图片加载
    DefaultAvatar(
        name = fallbackName,
        size = size,
        modifier = modifier
    )
}

/**
 * 默认头像组件
 */
@Composable
fun DefaultAvatar(
    name: String,
    size: androidx.compose.ui.unit.Dp = 48.dp,
    modifier: Modifier = Modifier
) {
    // 10张不同的风景和动漫头像URL
    val defaultAvatars = listOf(
        "https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=150&h=150&fit=crop&crop=center", // 山景
        "https://images.unsplash.com/photo-1441974231531-c6227db76b6e?w=150&h=150&fit=crop&crop=center", // 森林
        "https://images.unsplash.com/photo-1439066615861-d1af74d74000?w=150&h=150&fit=crop&crop=center", // 湖泊
        "https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=150&h=150&fit=crop&crop=center", // 海滩
        "https://images.unsplash.com/photo-1519501025264-65ba15a82390?w=150&h=150&fit=crop&crop=center", // 城市
        "https://images.unsplash.com/photo-1444927714506-8492d94b5ba0?w=150&h=150&fit=crop&crop=center", // 星空
        "https://images.unsplash.com/photo-1490750967868-88aa4486c946?w=150&h=150&fit=crop&crop=center", // 花朵
        "https://images.unsplash.com/photo-1513475382585-d06e58bcb0e0?w=150&h=150&fit=crop&crop=center", // 云朵
        "https://images.unsplash.com/photo-1416879595882-3373a0480b5b?w=150&h=150&fit=crop&crop=center", // 日落
        "https://images.unsplash.com/photo-1421789497144-f50500b5fcf0?w=150&h=150&fit=crop&crop=center"  // 雪景
    )
    
    // 根据用户名选择头像（确保同一用户总是显示同一张头像）
    val avatarIndex = remember(name) {
        name.hashCode().mod(10).let { if (it < 0) it + 10 else it }
    }
    
    val selectedAvatarUrl = defaultAvatars[avatarIndex]
    
    // 使用AsyncImage加载默认头像
    AsyncImage(
        model = selectedAvatarUrl,
        contentDescription = "默认头像",
        modifier = modifier
            .size(size)
            .clip(CircleShape),
        contentScale = ContentScale.Crop,
        error = painterResource(id = R.drawable.person),
        placeholder = painterResource(id = R.drawable.person)
    )
}

/**
 * 头像选择器组件
 */
@Composable
fun AvatarSelector(
    currentAvatar: String?,
    currentName: String,
    onAvatarSelected: (Bitmap) -> Unit,
    onDefaultAvatarSelected: (String) -> Unit,
    modifier: Modifier = Modifier
) {
    var showDialog by remember { mutableStateOf(false) }
    var showDefaultAvatarDialog by remember { mutableStateOf(false) }
    var isUploading by remember { mutableStateOf(false) }
    val context = LocalContext.current
    
    // 相册选择器
    val galleryLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent()
    ) { uri ->
        uri?.let {
            // 处理选择的图片 - 将Uri转换为Bitmap
            try {
                val inputStream = context.contentResolver.openInputStream(uri)
                val bitmap = android.graphics.BitmapFactory.decodeStream(inputStream)
                inputStream?.close()
                bitmap?.let { bmp ->
                    Log.e("AvatarSelector", "🔥 相册选择图片成功，尺寸: ${bmp.width}x${bmp.height}")
                    onAvatarSelected(bmp)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
    
    // 拍照选择器
    val cameraLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.TakePicturePreview()
    ) { bitmap ->
        bitmap?.let {
            Log.e("AvatarSelector", "🔥 拍照成功，尺寸: ${it.width}x${it.height}")
            onAvatarSelected(it)
        }
    }
    
    // 头像显示区域
    Box(
        modifier = modifier.clickable { showDialog = true },
        contentAlignment = Alignment.Center
    ) {
        if (currentAvatar != null && currentAvatar.isNotEmpty()) {
            SimpleAvatarImage(
                avatarUrl = currentAvatar,
                fallbackName = currentName,
                size = 80.dp
            )
        } else {
            DefaultAvatar(
                name = currentName,
                size = 80.dp
            )
        }
        
        // 编辑图标
        Box(
            modifier = Modifier
                .align(Alignment.BottomEnd)
                .size(24.dp)
                .clip(CircleShape)
                .background(MaterialTheme.colorScheme.primary),
            contentAlignment = Alignment.Center
        ) {
            Icon(
                imageVector = Icons.Default.CameraAlt,
                contentDescription = "编辑头像",
                tint = MaterialTheme.colorScheme.onPrimary,
                modifier = Modifier.size(16.dp)
            )
        }
    }
    
    // 头像选择对话框
    if (showDialog) {
        AvatarSelectionDialog(
            currentAvatar = currentAvatar,
            currentName = currentName,
            isUploading = isUploading,
            onSelectFromGallery = {
                galleryLauncher.launch("image/*")
                showDialog = false
            },
            onTakePhoto = {
                cameraLauncher.launch(null)
                showDialog = false
            },
            onUseDefaultAvatar = {
                // 显示默认头像选择对话框
                showDefaultAvatarDialog = true
                showDialog = false
            },
            onDismiss = { showDialog = false }
        )
    }
    
    // 默认头像选择对话框
    if (showDefaultAvatarDialog) {
        DefaultAvatarSelectionDialog(
            onAvatarSelected = { avatarUrl ->
                onDefaultAvatarSelected(avatarUrl)
                showDefaultAvatarDialog = false
            },
            onDismiss = { showDefaultAvatarDialog = false }
        )
    }
}